using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace LocalizationWpfDemo.Localization;

public sealed class LocalizationProvider : INotifyPropertyChanged
{
    private string _initLanguage;
    private IDictionary<string, string> _localizedValues;
    private readonly Dictionary<string, IYamlCSharpDictionary[]> _allLang;

    public event PropertyChangedEventHandler? PropertyChanged;

    public string CurrentLanguage
    {
        get => _initLanguage;
        set
        {
            Update(value);
            SetField(ref _initLanguage, value);
        }
    }

    public string this[string key] => GetLang(key);
    
    public LocalizationProvider(string initLanguage)
    {
        _initLanguage = initLanguage;

        _allLang = new Dictionary<string, IYamlCSharpDictionary[]>
        {
            { "en_US", [new en_US.Main()] },
            { "zh_CN", [new zh_CN.Main()] },
        };
        _localizedValues = _allLang[initLanguage].SelectMany(x => x.AsDictionary()).ToDictionary();
    }

    public string GetLang(string key)
    {
        key = "Lang." + key;
        if (_localizedValues.TryGetValue(key, out var value))
        {
            return value;
        }
        return "";
    }

    private void Update(string lang)
    {
        _localizedValues = _allLang[lang].SelectMany(x => x.AsDictionary()).ToDictionary();
    }

    private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private bool SetField<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
            return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}
